package com.viknix.threadpool.manager.client.message;

import com.viknix.threadpool.manager.client.core.DynamicThreadPoolExecutor;
import com.viknix.threadpool.manager.client.config.ApplicationContextHolder;
import com.viknix.threadpool.manager.common.model.PoolParameterInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: Dongqi
 * @Date: 2021/10/22 13:31
 * @Version 1.0
 * @Description: 消息发生器
 */
@Slf4j
public class SendMessageServiceImpl implements InitializingBean, SendMessageService {

    /**
     * 在自动配置的时候通过@Bean注入
     */
    private List<MessageReceiver> alarmConfigs;

    private final List<SendMessageHandler> sendMessageHandlers = new ArrayList(4);

    public SendMessageServiceImpl(List<MessageReceiver> alarmConfigs) {
        this.alarmConfigs = alarmConfigs;
    }

    /**
     * 发送告警信息
     *
     * @param threadPoolExecutor 动态线程池
     */
    @Override
    public void sendAlarmMessage(DynamicThreadPoolExecutor threadPoolExecutor) {
        // 遍历所有的Handler，发送消息
        for (SendMessageHandler messageHandler : sendMessageHandlers) {
            try {
                messageHandler.sendAlertorMessage(alarmConfigs, threadPoolExecutor);
            } catch (Exception e) {
                log.warn(">>> [😒 Failed to send thread pool alarm notification] : {}", e);
            }
        }
    }

    /**
     * 发送变更配置信息
     *
     * @param newParameter 新的线程池配置信息
     * @param oldParameter 旧的线程池配置信息
     */
    @Override
    public void sendChangeMessage(PoolParameterInfo newParameter, PoolParameterInfo oldParameter) {
        for (SendMessageHandler messageHandler : sendMessageHandlers) {
            try {
                messageHandler.sendChangeMessage(alarmConfigs, newParameter, oldParameter);
            } catch (Exception e) {
                log.warn(">>> [😒 Failed to send thread pool change notification] : {}", e);
            }
        }
    }

    /**
     * 在初始化完成后将所有SendMessageHandler放到集合当中（目前只对接了叮叮）
     */
    @Override
    public void afterPropertiesSet() {
        Map<String, SendMessageHandler> sendMessageHandlerMap = ApplicationContextHolder.getBeansOfType(SendMessageHandler.class);
        sendMessageHandlerMap.values().forEach(each -> sendMessageHandlers.add(each));
    }
}
